package com.andon.lcz.h264rtmp.pusher;

import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import com.andon.lcz.h264rtmp.params.AudioParam;

public class AudioPusher extends Pusher {

    private AudioRecord audioRecord;

    // 编码时输入的样本数
    private int inputSamples;

    public AudioPusher(AudioParam audioParam, PusherNative pusherNative) {
        super(pusherNative);
        int channelConfig = audioParam.getChannels() == 1 ?
                AudioFormat.CHANNEL_IN_MONO : AudioFormat.CHANNEL_IN_STEREO;
        int minBufferSize = AudioRecord.getMinBufferSize(audioParam.getSampleRateInHZ(),
                channelConfig,
                AudioFormat.ENCODING_PCM_16BIT);
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                audioParam.getSampleRateInHZ(),
                channelConfig,
                AudioFormat.ENCODING_PCM_16BIT,
                minBufferSize);
        pusherNative.setAudioOptions(audioParam.getSampleRateInHZ(), audioParam.getChannels());
        inputSamples = pusherNative.getInputSamples();
    }

    @Override
    public void start() {
        super.start();
        new Thread(new AudioRecordRunnable()).start();
    }

    class AudioRecordRunnable implements Runnable {

        @Override
        public void run() {
            audioRecord.startRecording();
            while (isPushing) {
                byte[] buffer = new byte[inputSamples * 2];
                int read = audioRecord.read(buffer, 0, buffer.length);
                if (read > 0) {
                    pusherNative.pushAudio(buffer, read);
                }
            }
            audioRecord.stop();
        }
    }

    @Override
    public void stop() {
        super.stop();
    }

    @Override
    public void release() {

    }
}
